package logic

import (
	"book/models/cache"
	"book/models/mysql"
	"context"
	"encoding/json"
	"fmt"
	"time"

	"book/bookrpc/bookrpc"
	"book/bookrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookListLogic {
	return &BookListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BookListLogic) BookList(in *bookrpc.BookListRequest) (*bookrpc.BookListResponse, error) {
	// todo: add your logic here and delete this line

	var books []mysql.BookData

	offset := (in.Page - 1) * in.Size

	key := fmt.Sprintf("bookList%v", in)

	result, _ := cache.RDB.Get(l.ctx, key).Result()

	if result == "" {

		tx := mysql.DB.Debug().Model(&mysql.Book{}).
			Select("books.*, users.`name` as user_name, classes.`name` as class_name").
			Joins("LEFT JOIN users ON users.id = books.user_id").
			Joins("LEFT JOIN classes on classes.id = books.class_id").
			Offset(int(offset)).Limit(int(in.Size))

		if in.UserName != "" {
			tx.Where("users.name like ?", "%"+in.UserName+"%")
		}

		if in.BookName != "" {
			tx.Where("books.title like ?", "%"+in.BookName+"%")
		}

		if in.ClassName != "" {
			tx.Where("classes.name like ?", "%"+in.ClassName+"%")
		}

		if in.OrderType != "" && in.FiledType != "" {
			tx.Order(in.FiledType + " " + in.OrderType)
		}

		tx.Find(&books)

		marshal, _ := json.Marshal(books)

		cache.RDB.Set(l.ctx, key, marshal, time.Minute*30)

	} else {
		json.Unmarshal([]byte(result), &books)
	}

	var bookList []*bookrpc.BookList

	for _, book := range books {
		list := bookrpc.BookList{
			UserName:     book.UserName,
			ClassName:    book.ClassName,
			Title:        book.Title,
			Image:        book.Image,
			Context:      book.Context,
			BookId:       int64(book.ID),
			BrowseNumber: book.BrowseNumber,
		}

		bookList = append(bookList, &list)
	}

	return &bookrpc.BookListResponse{
		List: bookList,
	}, nil
}
